from minio import Minio
from minio.error import S3Error

def upload_file(client, bucket_name, file_path, object_name):
    try:
        client.fput_object(bucket_name, object_name, file_path)
        print(f"{file_path} is successfully uploaded as {object_name}.")
    except S3Error as err:
        print(err)

def download_file(client, bucket_name, object_name, file_path):
    try:
        client.fget_object(bucket_name, object_name, file_path)
        print(f"{object_name} is successfully downloaded to {file_path}.")
    except S3Error as err:
        print(err)

def read_file_content(file_path):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
            print(f"File content:\n{content}")
    except IOError as err:
        print(err)

def main():
    # MinIO client configuration
    client = Minio(
        "127.0.0.1:51531",
        access_key="minioadmin",
        secret_key="minioadmin",
        secure=False
    )

    bucket_name = "mybucket"
    file_path = r"D:\03_files\08_交付\生成代码\minio\1.txt"
    object_name = "1.txt"
    downloaded_file_path = r"D:\03_files\08_交付\生成代码\minio\downloaded_1.txt"

    # Create bucket if not exists
    if not client.bucket_exists(bucket_name):
        client.make_bucket(bucket_name)
        print(f"Bucket {bucket_name} created.")

    # Upload file
    upload_file(client, bucket_name, file_path, object_name)

    # Download file
    download_file(client, bucket_name, object_name, downloaded_file_path)

    # Read file content
    read_file_content(downloaded_file_path)

if __name__ == "__main__":
    main()
